package com.ctsi.framework.mybatis.dialect;

import java.sql.PreparedStatement;
import java.sql.SQLException;


/**
 * DB2的分页数据库方言实现
 * @author zhangjw
 */
public class DB2Dialect extends AbstractMiDialect{


	@Override
	public void setLimitParamters(PreparedStatement ps, int parameterSize,
			int offset, int limit) throws SQLException {
		if(offset >= 0){
			ps.setInt(parameterSize + 1, offset);
			ps.setInt(parameterSize + 2, offset + limit);
		}else{
			ps.setInt(parameterSize + 1, limit);
		}
	}

	@Override
	public String getLimitString(String sql, int offset) {
		sql = sql.toUpperCase();
		StringBuilder rownumber = new StringBuilder(sql.length() + 100).append("select  rownumber() over(");
		rownumber.append(") as rownum_,tem_.* from (").append(sql).append(") tem_");

		StringBuilder pagingSelect = new StringBuilder(sql.length() + 100).append("select * from ( ").append(rownumber).append(" )  where rownum_ ");
		if (offset >= 0) {
			pagingSelect.append("> ? and rownum_ <= ?");
		} else {
			pagingSelect.append("<= ?");
		}
		return pagingSelect.toString();
	}

	@Override
	public boolean supportsLimitOffset() {
		
		return true;
	}

}
